﻿using Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using ServiceCore;
using ServiceCore.Tool.Wx;
using ServiceCore.Tool.Wx.diy_menu;
using ServiceCore.Tool.Wx.media;
using ServiceCore.Tool.Wx.wx_msg;
using ServiceCore.Tool.Xml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Dapper;

namespace Customer.Bussiness_Service
{
    public interface Iwx_service
    {
        /// <summary>
        /// 微信服务器验证
        /// </summary>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <param name="echostr"></param>
        /// <returns></returns>
        string server_auth(string signature, string timestamp, string nonce, string echostr);
        string wx_msg(string xml_data);
        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <returns></returns>
        ResultObjModel diy_menu_get();
        /// <summary>
        /// 修改菜单列表
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        ResultObjModel diy_menu_create(menu_create_params Params);



        #region 素材库
        /// <summary>
        /// 添加永久图文素材
        /// </summary>
        /// <param name="add_list"></param>
        /// <returns></returns>
        ResultObjModel add_news(List<add_news_articles_item> add_list);
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        ResultObjModel uploadimg(IFormFileCollection files);
        /// <summary>
        /// 添加其他永久素材
        /// </summary>
        /// <param name="files"></param>
        /// <param name="type"></param>
        /// <param name="title"></param>
        /// <param name="introduction"></param>
        /// <returns></returns>
        ResultObjModel add_material(IFormFileCollection files, string type, string title, string introduction);
        /// <summary>
        ///  获取素材库列表
        /// </summary>
        /// <param name="type"></param>
        /// <param name="pagesize"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        ResultObjModel batchget_material(string type, int pagesize = 20, int page = 1);
        /// <summary>
        /// 获取单个素材
        /// </summary>
        /// <param name="type"></param>
        /// <param name="media_id"></param>
        /// <returns></returns>
        ResultObjModel get_material(string type, string media_id);
        /// <summary>
        /// 获取素材数量
        /// </summary>
        /// <returns></returns>
        ResultObjModel get_materialcount();
        /// <summary>
        /// 删除指定素材
        /// </summary>
        /// <param name="media_id"></param>
        /// <returns></returns>
        ResultModel del_material(string media_id);
        /// <summary>
        /// 更新永久图文消息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        ResultModel update_news(update_news_params model);
        /// <summary>
        /// 设置关注回复
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        ResultObjModel set_follow_return(set_follow_return_params Params);
        /// <summary>
        /// 设置关键词回复
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        ResultObjModel set_key_return(set_key_return_params Params);
        /// <summary>
        /// 设置按钮点击回复
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        ResultObjModel set_click_return(set_click_return_params Params);
        /// <summary>
        /// 设置返回数据
        /// </summary>
        /// <param name="message_id"></param>
        /// <param name="is_use"></param>
        /// <returns></returns>
        ResultObjModel set_msg_return_use(string message_id, bool? is_use);

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        ResultListModel<wx_message_base> get_wx_msg_pagelist(get_wx_message_pagelist_params Params);
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="message_id"></param>
        /// <returns></returns>
        ResultObjModel del_wx_msg(string message_id);
        #endregion
    }
    public class wx_service : Iwx_service
    {
        private readonly IToole_DI _tool;
        private readonly IConfiguration _appSettingConfig;
        private readonly Idiy_menu_service _diymenu_service;

        private readonly Iwx_media_service _media_service;
        public wx_service(IToole_DI Tool, IConfiguration AppSettingConfig, Idiy_menu_service Diymenu_service, Iwx_media_service Media_service)
        {
            _tool = Tool;
            _appSettingConfig = AppSettingConfig;
            _diymenu_service = Diymenu_service;
            _media_service = Media_service;
        }

        public string server_auth(string signature, string timestamp, string nonce, string echostr)
        {
            if (Check(signature, timestamp, nonce, null))
            {
                return echostr;//返回随机字符串则表示验证通过
            }
            else
            {
                return "fail";
            }
        }
        /// <summary>
        /// 指定控制的微信公众号信息
        /// </summary>
        private string set_appid
        {
            get { return _appSettingConfig["wx_server:appid"].ToString(); }
        }

        #region 服务器模式 
        /// <summary>
        /// 检查签名是否正确
        /// </summary>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        private bool Check(string signature, string timestamp, string nonce, string token = null)
        {
            return signature == GetSignature(timestamp, nonce, token);
        }
        /// <summary>
        /// 返回正确的签名
        /// </summary>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        private string GetSignature(string timestamp, string nonce, string token = null)
        {
            token = token ?? _appSettingConfig["wx_server:token"];
            var arr = new[] { token, timestamp, nonce }.OrderBy(z => z).ToArray();
            var arrString = string.Join("", arr);
            //var enText = FormsAuthentication.HashPasswordForStoringInConfigFile(arrString, "SHA1");//使用System.Web.Security程序集
            var sha1 = System.Security.Cryptography.SHA1.Create();
            var sha1Arr = sha1.ComputeHash(Encoding.UTF8.GetBytes(arrString));
            StringBuilder enText = new StringBuilder();
            foreach (var b in sha1Arr)
            {
                enText.AppendFormat("{0:x2}", b);
            }
            return enText.ToString();
        }
        #endregion
        #region 3X5菜单 
        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <returns></returns>
        public ResultObjModel diy_menu_get()
        {
            return CoreStartDo.ResultAction(result =>
            {
                result.code = 0;
                result.msg = "success";
                result.data = _diymenu_service.diy_menu_get();
                return result;
            });
        }
        /// <summary>
        /// 修改菜单列表
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        public ResultObjModel diy_menu_create(menu_create_params Params)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (Params == null || Params.button == null || !Params.button.Any())
                {
                    result.code = 1;
                    result.msg = "不能提交空数据";
                }
                int btn_index = 1;
                foreach (var item in Params.button)
                {
                    item.key = $"btn_{btn_index}";
                    int sub_btn_index = 1;
                    if (item.sub_button != null && item.sub_button.Any())
                    {
                        foreach (var sub_item in item.sub_button)
                        {
                            sub_item.key = $"btn_{btn_index}_{sub_btn_index}";
                            sub_btn_index++;
                        }
                    }
                    btn_index++;
                }
                result.code = 0;
                result.msg = "success";
                result.data = _diymenu_service.diy_menu_create(Params);
                return result;
            });
        }



        #endregion
        #region 设置消息返回 
        public string wx_msg(string xml_data)
        {
            return base_msg_func.start_analysis(xml_data, (msg_type, obj) =>
            {
                string reply_str = "";
                switch (msg_type)
                {
                    case "text":
                        text_msg text = obj as text_msg;
                        text_msg_reply(text, ref reply_str);
                        break;
                    case "image":
                        image_msg image = obj as image_msg;
                        reply_str = "success";
                        break;
                    case "voice":
                        voice_msg voice = obj as voice_msg;
                        reply_str = "success";
                        break;
                    case "video":
                        video_msg video = obj as video_msg;
                        reply_str = "success";
                        break;
                    case "shortvideo":
                        shortvideo_msg shortvideo = obj as shortvideo_msg;
                        reply_str = "success";
                        break;
                    case "location":
                        location_msg location = obj as location_msg;
                        reply_str = "success";
                        break;
                    case "link":
                        link_msg link = obj as link_msg;
                        reply_str = "success";
                        break;
                    case "event":
                        //当前是事件推送 需要重解析
                        reply_str = event_reply(xml_data);
                        break;
                    default:
                        //不认识的玩意
                        reply_str = "success";
                        break;
                }
                if (string.IsNullOrWhiteSpace(reply_str))
                {
                    reply_str = "success";
                }
                return reply_str;
            });
        }
        /// <summary>
        ///  关键字回复 
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="replay"></param>
        private void text_msg_reply(text_msg msg, ref string replay)
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            var db_msg = _tool.di_db.GetList<wx_message_base>("select * from wx_message_base where mp_app_id=@mp_app_id and message_type=@message_type and key_parameter=@key_parameter and is_use=@is_use", new
            {
                mp_app_id = set_appid,
                message_type = message_type.关键词回复,
                key_parameter = msg.Content,
                is_use = true
            }).FirstOrDefault();
            if (db_msg == null)
            {
                replay = "success";
            }
            else
            {
                replay = return_wx_xml_data<DBNull>(msg.ToUserName, msg.FromUserName, db_msg);
            }
        }
        /// <summary>
        /// 返回微信模板消息统一模板
        /// </summary>
        /// <param name="ToUserName"></param>
        /// <param name="FromUserName"></param>
        /// <param name="set_data"></param>
        /// <returns></returns>
        private string return_wx_xml_data<T>(string ToUserName, string FromUserName, wx_message_base set_data, Func<T> default_do = null)
        { 
            switch (set_data.msg_type)
            {
                case "text":
                    reply_text_msg text = DeserializeObject<reply_text_msg>(set_data.json_content); 
                    text.MsgType = set_data.msg_type;
                    text.FromUserName = ToUserName;
                    text.ToUserName = FromUserName;
                    return XMLConvert.ToXml(text);
                case "image":
                    reply_image_msg image = DeserializeObject<reply_image_msg>(set_data.json_content); 
                    image.MsgType = set_data.msg_type;
                    image.FromUserName = ToUserName;
                    image.ToUserName = FromUserName;
                    return XMLConvert.ToXml(image);
                case "voice":
                    reply_voice_msg voice = DeserializeObject<reply_voice_msg>(set_data.json_content); 
                    voice.MsgType = set_data.msg_type;
                    voice.FromUserName = ToUserName;
                    voice.ToUserName = FromUserName;
                    return XMLConvert.ToXml(voice);
                case "video":
                    reply_video_msg video = DeserializeObject<reply_video_msg>(set_data.json_content); 
                    video.MsgType = set_data.msg_type;
                    video.FromUserName = ToUserName;
                    video.ToUserName = FromUserName;
                    return XMLConvert.ToXml(video);
                case "news":
                    reply_news_msg news = DeserializeObject<reply_news_msg>(set_data.json_content); 
                    news.MsgType = set_data.msg_type;
                    news.FromUserName = ToUserName;
                    news.ToUserName = FromUserName;
                    return XMLConvert.ToXml(news);
                default:
                    if (default_do == null)
                    {
                        return "success";
                    }
                    else
                    {
                        T send_obj = default_do();
                        return XMLConvert.ToXml(send_obj);
                    }
            }
        }
        /// <summary>
        /// 重新处理关注事件
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        private string event_reply(string xml)
        { 
            return base_msg_func.start_analysis(xml, (event_type, obj) =>
            {
                
                string reply_str = "";
                switch (event_type)
                {
                    case "subscribe":
                        event_subscribe_msg subscribe = obj as event_subscribe_msg; 
                        //如果没有参数，则直接返回关注回复
                        if (!string.IsNullOrWhiteSpace(subscribe.EventKey))
                        {
                            //开始解析 目前没有这个功能 直接返回success
                            reply_str = "success";
                        }
                        else
                        { 
                            //直接返回设置的关注回复
                            wx_message_base set_subscribe_data = _tool.di_db.GetList<wx_message_base>("select top 1 * from wx_message_base where mp_app_id=@mp_app_id and is_use=@is_use and message_type=@message_type ", new
                            {
                                mp_app_id = set_appid,
                                is_use = true,
                                message_type = message_type.关注回复
                            }).FirstOrDefault();
                            if (set_subscribe_data == null)
                            {
                                reply_str = XMLConvert.ToXml(new reply_text_msg()
                                {
                                    ToUserName = subscribe.FromUserName,
                                    FromUserName = subscribe.ToUserName, 
                                    MsgType = "text",
                                    Content = "感谢您的关注"
                                });
                            }
                            else
                            { 
                                reply_str = return_wx_xml_data(subscribe.ToUserName, subscribe.FromUserName, set_subscribe_data, () =>
                                {
                                    return new reply_text_msg()
                                    {
                                        ToUserName = subscribe.FromUserName,
                                        FromUserName = subscribe.ToUserName, 
                                        MsgType = "text",
                                        Content = "感谢您的关注"
                                    };
                                }); 
                            }
                        } 
                        break;
                    case "unsubscribe":
                        event_unsubscribe_msg unsubscribe = obj as event_unsubscribe_msg;
                        reply_str = "unsubscribe";
                        break;
                    case "scan":
                        event_scan_msg scan = obj as event_scan_msg;
                        reply_str = Newtonsoft.Json.JsonConvert.SerializeObject(new
                        {
                            scan.EventKey,
                            scan.Ticket
                        });
                        break;
                    case "location":
                        event_location_msg location = obj as event_location_msg;
                        reply_str = Newtonsoft.Json.JsonConvert.SerializeObject(new
                        {
                            location.Latitude,
                            location.Longitude,
                            location.Precision
                        });
                        break;
                    case "click":
                        event_click_msg click = obj as event_click_msg; 
                        //直接返回设置的关注回复
                        var set_click_data = _tool.di_db.GetList<wx_message_base>("select top 1 * from wx_message_base where mp_app_id=@mp_app_id and message_type=@message_type and key_parameter=@key_parameter  and is_use=@is_use", new
                        {
                            mp_app_id = set_appid,
                            is_use = true,
                            message_type = message_type.菜单click,
                            key_parameter = click.EventKey
                        }).FirstOrDefault();
                        if (set_click_data == null)
                        {
                            reply_str = XMLConvert.ToXml(new reply_text_msg()
                            {
                                ToUserName = click.FromUserName,
                                FromUserName = click.ToUserName, 
                                MsgType = "text",
                                Content = "未设置响应信息"
                            });
                        }
                        else
                        { 
                            reply_str = return_wx_xml_data(click.ToUserName, click.FromUserName, set_click_data, () =>
                            {
                                return new reply_text_msg()
                                {
                                    ToUserName = click.FromUserName,
                                    FromUserName = click.ToUserName,
                                    MsgType = "text",
                                    Content = "未知的响应信息"
                                };
                            });
                        }
                        break;
                    case "view":
                        event_view_msg view = obj as event_view_msg;
                        reply_str = "success";//view.EventKey;
                        break;
                    default:
                        //不认识的玩意
                        reply_str = "success";
                        break;
                }
                if (string.IsNullOrWhiteSpace(reply_str))
                {
                    reply_str = "success";
                }
                return reply_str;
            }, true);
        } 
        #endregion 
        #region 微信素材库管理
        /// <summary>
        /// 添加永久图文素材
        /// </summary>
        /// <param name="add_list"></param>
        /// <returns></returns>
        public ResultObjModel add_news(List<add_news_articles_item> add_list)
        {
            return CoreStartDo.ResultAction(result =>
            {
                var add_news = _media_service.add_news(add_list);
                if (add_news.errcode == 0)
                {
                    result.code = 0;
                    result.msg = add_news.errmsg;
                    result.data = new
                    {
                        add_news.media_id
                    };
                }
                else
                {
                    result.code = 1;
                    result.msg = add_news.errmsg;
                }
                return result;
            });
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        public ResultObjModel uploadimg(IFormFileCollection files) {
            return CoreStartDo.ResultAction(result =>
            {
                if (files.Count == 0)
                {
                    result.code = 0;
                    result.msg = "上传文件失败:提交任何文件";
                    return result;
                }
                var wx_result = _media_service.uploadimg(files[0]);
                if (wx_result.errcode == 0)
                {
                    result.code = 0;
                    result.msg = "success";
                    result.data = new
                    {
                        wx_result.url
                    };
                }
                else {
                    result.code = 1;
                    result.msg = wx_result.errmsg; 
                }
                return result;
            });
        } 
        /// <summary>
        /// 添加永久其他素材
        /// </summary>
        /// <param name="add_list"></param>
        /// <returns></returns>
        public ResultObjModel add_material(IFormFileCollection files, string type, string title, string introduction)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (files.Count == 0)
                {
                    result.code = 1;
                    result.msg = "未检测到任何上传的素材文件";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(type))
                {
                    result.code = 1;
                    result.msg = "素材类型不能为空";
                    return result;
                } 
                var add_material = _media_service.add_material(files[0], type, title, introduction);
                if (add_material.errcode == 0)
                {
                    result.code = 0;
                    result.msg = add_material.errmsg;
                    result.data = new
                    {
                        add_material.media_id,
                        add_material.url
                    };
                }
                else
                {
                    result.code = 1;
                    result.msg = add_material.errmsg;
                }
                return result;
            });
        }
        /// <summary>
        /// 获取素材列表
        /// </summary>
        /// <returns></returns>
        public ResultObjModel batchget_material(string type, int pagesize = 20, int page = 1)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(type))
                {
                    result.code = 1;
                    result.msg = "未能获取请求素材库类型";
                }
                var batchget_material = _media_service.batchget_material(type, pagesize, (page - 1) * pagesize);
                if (batchget_material.errcode == 0)
                {
                    result.code = 0;
                    result.msg = "success";
                    result.data = new
                    {
                        batchget_material.total_count,
                        batchget_material.item_count,
                        batchget_material.item
                    };
                }
                else
                {
                    result.code = 1;
                    result.msg = batchget_material.errmsg;
                }
                return result;
            });
        } 
        /// <summary>
        /// 获取单个素材，目前只有news操作
        /// </summary>
        /// <returns></returns>
        public ResultObjModel get_material(string type,string media_id) {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(type))
                {
                    result.code = 1;
                    result.msg = "未能获取类型";
                    return result;
                }
                if (!new string[] { "news", "video" }.Contains(type))
                {
                    result.code = 1;
                    result.msg = "目前不支持该种类型请求";
                    return result;
                }
                var get_material = _media_service.get_material(media_id);
                if (get_material.errcode == 0)
                {
                    result.code = 0;
                    result.msg = "success";
                    result.data = new
                    {
                        get_material.description,
                        get_material.down_url,
                        get_material.title,
                        get_material.news_item
                    };
                }
                else
                {
                    result.code = 1;
                    result.msg = get_material.errmsg;
                }
                return result;
            });
        }

        /// <summary>
        ///  获取素材数量
        /// </summary>
        /// <returns></returns>
        public ResultObjModel get_materialcount()
        {
            return CoreStartDo.ResultAction(result =>
            {

                var get_materialcount = _media_service.get_materialcount();
                if (get_materialcount.errcode == 0)
                {
                    result.code = 0;
                    result.msg = "success";
                    result.data = new
                    {
                        get_materialcount.image_count,
                        get_materialcount.video_count,
                        get_materialcount.voice_count,
                        get_materialcount.news_count
                    };
                }
                else
                {
                    result.code = 1;
                    result.msg = get_materialcount.errmsg;
                }
                return result;
            });
        }

        /// <summary>
        ///  删除指定素材
        /// </summary>
        /// <returns></returns>
        public ResultModel del_material(string media_id)
        {
            return CoreStartDo.ResultAction(result =>
            {
                var del_material = _media_service.del_material(media_id);
                if (del_material.errcode == 0)
                {
                    result.code = 0;
                    result.msg = "删除成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = del_material.errmsg;
                }
                return result;
            });
        }
        /// <summary>
        ///  更新永久图文素材信息
        /// </summary>
        /// <returns></returns>
        public ResultModel update_news(update_news_params model)
        {
            return CoreStartDo.ResultAction(result =>
            {
                var update_news = _media_service.update_news(model);
                if (update_news.errcode == 0)
                {
                    result.code = 0;
                    result.msg = "修改成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = update_news.errmsg;
                }
                return result;
            });
        }
        #endregion 
        #region 设置关注回复 
        /// <summary>
        /// 设置关注回复
        /// </summary>
        /// <returns></returns>
        public ResultObjModel set_follow_return(set_follow_return_params Params)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(Params.msg_type))
                {
                    result.code = 1;
                    result.msg = "消息类型不能为空";
                    return result;
                }
                string json_content = ""; 
                result = check_msg_type(Params.msg_type, Params.json_content, ref json_content);
                if (result.code == 1)
                {
                    return result;
                }
                //数据保存
                wx_message_base new_model = new wx_message_base()
                {
                    is_use = Params.is_use,
                    addtime = DateTime.Now,
                    message_id = _tool.di_getid.IGet_SnowFlake_Id,
                    message_type = message_type.关注回复,
                    mp_app_id = set_appid,
                    key_parameter = "0",
                    json_content = json_content,//Newtonsoft.Json.JsonConvert.SerializeObject(Params.json_content),
                    msg_type = Params.msg_type
                };
                string error = "";
                //执行事务
                int tran_rows = _tool.di_db.StartTran((conn, tran) =>
                {
                    int rows = 0;
                    if (Params.is_use)
                    {
                        //将数据库内所有这个appid下的所有关注回复置换为不可用
                        rows += conn.Execute("update wx_message_base set is_use=@is_use where mp_app_id=@mp_app_id and message_type=@message_type and is_use=@old_is_use", new { is_use = false, old_is_use = true, mp_app_id = set_appid, message_type = message_type.关注回复 }, tran);
                    }
                    rows += conn.Execute(_tool.di_db.AddBySqlStr<wx_message_base>(), new_model, tran);
                    return rows;
                }, ref error);
                if (string.IsNullOrWhiteSpace(error))
                {
                    result.code = 0;
                    result.msg = "保存成功"; 
                }
                else
                {
                    result.code = 1;
                    result.msg = $"保存失败:{error}";
                }
                return result;
            });
        } 
        /// <summary>
        /// 设置关键词回复
        /// </summary>
        /// <returns></returns>
        public ResultObjModel set_key_return(set_key_return_params Params) {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(Params.key_parameter))
                {
                    result.code = 1;
                    result.msg = "未设置任何关键词";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(Params.msg_type))
                {
                    result.code = 1;
                    result.msg = "消息类型不能为空";
                    return result;
                }
                string json_content = "";
                result = check_msg_type(Params.msg_type, Params.json_content, ref json_content);
                if (result.code == 1)
                {
                    return result;
                }
                //数据保存
                wx_message_base new_model = new wx_message_base()
                {
                    is_use = Params.is_use,
                    addtime = DateTime.Now,
                    message_id = _tool.di_getid.IGet_SnowFlake_Id,
                    message_type = message_type.关键词回复,
                    mp_app_id = set_appid,
                    key_parameter = Params.key_parameter,
                    json_content = json_content,//Newtonsoft.Json.JsonConvert.SerializeObject(Params.json_content),
                    msg_type = Params.msg_type
                };
                string error = "";
                //执行事务
                int tran_rows = _tool.di_db.StartTran((conn, tran) =>
                {
                    int rows = 0;
                    if (Params.is_use)
                    {
                        //将数据库内所有这个appid下的所有关注回复置换为不可用
                        rows += conn.Execute("update wx_message_base set is_use=@is_use where mp_app_id=@mp_app_id and message_type=@message_type and is_use=@old_is_use and key_parameter=@key_parameter", new { is_use = false, old_is_use = true, mp_app_id = set_appid, message_type = message_type.关键词回复, key_parameter = Params.key_parameter }, tran);
                    }
                    rows += conn.Execute(_tool.di_db.AddBySqlStr<wx_message_base>(), new_model, tran);
                    return rows;
                }, ref error);
                if (string.IsNullOrWhiteSpace(error))
                {
                    result.code = 0;
                    result.msg = "保存成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = $"保存失败:{error}";
                }
                return result;
            });
        }

        /// <summary>
        /// 设置点击事件返回
        /// </summary>
        /// <returns></returns>
        public ResultObjModel set_click_return(set_click_return_params Params)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (!Params.btn_index.HasValue)
                {
                    result.code = 1;
                    result.msg = "3X5菜单定义位置缺失:缺少主菜单位置";
                    return result;
                }
                if (Params.btn_index <= 0 || Params.btn_index > 3)
                {

                    result.code = 1;
                    result.msg = "主菜单位置定义异常";
                    return result;
                }
                if (!Params.sub_button_index.HasValue)
                {
                    result.code = 1;
                    result.msg = "3X5菜单定义位置缺失:缺少子菜单位置";
                    return result;
                }
                if (Params.sub_button_index < 0 || Params.sub_button_index > 5)
                {

                    result.code = 1;
                    result.msg = "子菜单位置定义异常";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(Params.msg_type))
                {
                    result.code = 1;
                    result.msg = "消息类型不能为空";
                    return result;
                }
                string key_parameter = $"btn_{Params.btn_index}"; 
                ///如果子菜单入参0 则认为没有子菜单
                if (Params.sub_button_index > 0)
                {
                    key_parameter += $"_{Params.sub_button_index}";
                }

                string json_content = "";
                result = check_msg_type(Params.msg_type, Params.json_content, ref json_content);
                if (result.code == 1)
                {
                    return result;
                }
                //数据保存
                wx_message_base new_model = new wx_message_base()
                {
                    is_use = Params.is_use,
                    addtime = DateTime.Now,
                    message_id = _tool.di_getid.IGet_SnowFlake_Id,
                    message_type = message_type.菜单click,
                    mp_app_id = set_appid,
                    key_parameter = key_parameter,
                    json_content = json_content,//Newtonsoft.Json.JsonConvert.SerializeObject(Params.json_content),
                    msg_type = Params.msg_type
                };
                string error = "";
                //执行事务
                int tran_rows = _tool.di_db.StartTran((conn, tran) =>
                {
                    int rows = 0;
                    if (Params.is_use)
                    {
                        //将数据库内所有这个appid下的所有关注回复置换为不可用
                        rows += conn.Execute("update wx_message_base set is_use=@is_use where mp_app_id=@mp_app_id and message_type=@message_type and is_use=@old_is_use and key_parameter=@key_parameter", new { is_use = false, old_is_use = true, mp_app_id = set_appid, message_type = message_type.菜单click, key_parameter = key_parameter }, tran);
                    }
                    rows += conn.Execute(_tool.di_db.AddBySqlStr<wx_message_base>(), new_model, tran);
                    return rows;
                }, ref error);
                if (string.IsNullOrWhiteSpace(error))
                {
                    result.code = 0;
                    result.msg = "保存成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = $"保存失败:{error}";
                }
                return result;
            });
        }
        /// <summary>
        /// 格式化数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        private T DeserializeObject<T>(string t_data) where T : wx_msg_base_model
        {
            try
            { 
                var result = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(t_data);
                var ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds;
                result.CreateTime = Convert.ToInt64(ts);
                return result;
            }
            catch
            {
                throw new Exception("格式化数据失败");
            }
        }
        private ResultObjModel check_msg_type(string msg_type, object json_content, ref string json_result)
        {
            ResultObjModel result = new ResultObjModel();
            switch (msg_type)
            {
                case "text":
                    reply_text_msg text = DeserializeObject<reply_text_msg>(Newtonsoft.Json.JsonConvert.SerializeObject(json_content));
                    if (string.IsNullOrWhiteSpace(text.Content))
                    {
                        result.code = 1;
                        result.msg = "设置文字异常:内容不能为空";
                        return result;
                    }
                    json_result = Newtonsoft.Json.JsonConvert.SerializeObject(text);
                    break;
                case "image":
                    reply_image_msg image = DeserializeObject<reply_image_msg>(Newtonsoft.Json.JsonConvert.SerializeObject(json_content));
                    if (image.Image == null || string.IsNullOrWhiteSpace(image.Image.MediaId))
                    {
                        result.code = 1;
                        result.msg = "设置图片异常:MediaId不能为空";
                        return result;
                    }
                    json_result = Newtonsoft.Json.JsonConvert.SerializeObject(image);
                    break;
                case "voice":
                    reply_voice_msg voice = DeserializeObject<reply_voice_msg>(Newtonsoft.Json.JsonConvert.SerializeObject(json_content));
                    if (voice.Voice == null || string.IsNullOrWhiteSpace(voice.Voice.MediaId))
                    {
                        result.code = 1;
                        result.msg = "设置语音异常:MediaId不能为空";
                        return result;
                    }
                    json_result = Newtonsoft.Json.JsonConvert.SerializeObject(voice);
                    break;
                case "video":
                    reply_video_msg video = DeserializeObject<reply_video_msg>(Newtonsoft.Json.JsonConvert.SerializeObject(json_content));
                    if (video.Video == null || string.IsNullOrWhiteSpace(video.Video.MediaId))
                    {
                        result.code = 1;
                        result.msg = "设置视频异常:MediaId不能为空";
                        return result;
                    }
                    json_result = Newtonsoft.Json.JsonConvert.SerializeObject(video);
                    break;
                case "news":
                    reply_news_msg news = DeserializeObject<reply_news_msg>(Newtonsoft.Json.JsonConvert.SerializeObject(json_content));
                    if (news.Articles == null || news.Articles.item == null || !news.Articles.item.Any())
                    {
                        result.code = 1;
                        result.msg = "设置多图文信息失败:至少设置一项";
                        return result;
                    }
                    json_result = Newtonsoft.Json.JsonConvert.SerializeObject(news);
                    break;
                default:
                    result.code = 1;
                    result.msg = "未知的消息类型";
                    return result;
            }
            result.code = 0;
            result.msg = "success";
            return result;
        }
        #endregion
        #region 后台操作
        /// <summary>
        /// 设置可用
        /// </summary>
        /// <returns></returns>
        public ResultObjModel set_msg_return_use(string message_id,bool? is_use)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(message_id))
                {
                    result.code = 1;
                    result.msg = "消息ID不能为空";
                    return result;
                }
                if (!is_use.HasValue)
                {
                    result.code = 1;
                    result.msg = "必须告知是否可用";
                    return result;
                }
                var updateinfo = _tool.di_db.GetList<wx_message_base>("select top 1 * from wx_message_base where message_id=@message_id", new { message_id }).FirstOrDefault();
                if (updateinfo == null)
                {
                    result.code = 1;
                    result.msg = "未能找到指定返回消息数据";
                    return result;
                } 
                string error = "";
                //执行事务
                int tran_rows = _tool.di_db.StartTran((conn, tran) =>
                {
                    int rows = 0;
                    if (is_use.Value)
                    {
                        //将数据库内所有这个appid下的所有关注回复置换为不可用
                        rows += conn.Execute("update wx_message_base set is_use=@is_use where mp_app_id=@mp_app_id and message_type=@message_type and is_use=@old_is_use", new { is_use = false, old_is_use = true, mp_app_id = updateinfo.mp_app_id, message_type = updateinfo.message_type }, tran);
                    }
                    rows += conn.Execute("update wx_message_base set is_use=@is_use where message_id=@message_id", new { message_id, is_use }, tran);
                    return rows;
                }, ref error);
                if (string.IsNullOrWhiteSpace(error))
                {
                    result.code = 0;
                    result.msg = "设置成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = $"设置失败:{error}";
                }

                return result;
            });
        }

        /// <summary>
        /// 获取卡列表信息
        /// </summary>
        /// <returns></returns>
        public ResultListModel<wx_message_base> get_wx_msg_pagelist(get_wx_message_pagelist_params Params)
        {
            return CoreStartDo.ResultAction<ResultListModel<wx_message_base>>(result =>
            {
                string sql = "select * from wx_message_base";
                string where = " where 1=1";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                where += " and mp_app_id=@mp_app_id";
                query_dy.mp_app_id = set_appid;
                if (Params.message_type.HasValue)
                {
                    where += " and message_type=@message_type";
                    query_dy.message_type = Params.message_type.Value;
                }
                if (Params.is_use.HasValue)
                {
                    where += " and is_use=@is_use";
                    query_dy.is_use = Params.is_use.Value;
                }
                if (!string.IsNullOrWhiteSpace(Params.msg_type))
                {
                    where += " and msg_type=@msg_type";
                    query_dy.msg_type = Params.msg_type;
                }
                var result_list = _tool.di_db.GetPageList<wx_message_base>(sql, where, "is_use", query_dy, Params.IsPage, Params.page, Params.pagesize);
                return result_list;
            });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ResultObjModel del_wx_msg(string message_id)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(message_id))
                {
                    result.code = 1;
                    result.data = "message_id不能为空";
                    return result;
                }
                var updateinfo = _tool.di_db.GetList<wx_message_base>("select top 1 * from wx_message_base where message_id=@message_id", new { message_id }).FirstOrDefault();
                if (updateinfo == null)
                {
                    result.code = 1;
                    result.msg = "未能找到指定返回消息数据";
                    return result;
                }
                var del_rows = _tool.di_db.do_Execute("delete from wx_message_base where message_id=@message_id", new { message_id });
              if(del_rows>0)
                {
                    result.code = 0;
                    result.msg = "删除成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = $"删除失败";
                }
                return result;
            });
        }
        #endregion
    }
}
